Pointers and Array

An array in C language, is the one which is allocated contiguous(continuous) memory location. So now using a pointer variable we can read the array of values.

Example

int x[5] = {10,20,30,40,50};

This will allocate memory in sequencial order like

x[0] = 1000 (address),
x[2] = 1002,
x[3] = 1003,
x[4] = 1004
x[5] = 1005

Now lets see an example to use a pointer variable to access the array of elements.

#include<stdio.h>

void main()
{
   int a[5] = {1, 2, 3, 4,5};
   int *p = a;    
   for (int i = 0; i < 5; i++)
   {
      printf("%d", *p);
      p++;
   }
  return 0;
}

Output

1 2 3 4 5

Here we have created an array variable a and assign it to a pointer variable. Note that, we have assigned a instead of assigning the address of a as &a.

Now the pointer will be pointing to the first element, when we increment the pointer variable like p++ it will point to the next element in the array a. So this way it prints the elements of an array.

Pointer to point Character String

Pointers can be used to create strings. The pointer variable of char type is treated as string.

Example

char *str = "ReadersBuddy";

This will create a string and stores its address to the pointer variable str. Initially, the str pointer variable points to the first character of ReadersBuddy.

We can assign value to a char pointer at runtime.

char *str;
str = "ReadersBuddy";
printf("%s",str);

Here we have created a pointer variable str of type character and assign a string ReadersBuddy and print it using printf() function.


Most Read